package com.app.util;

import android.util.Base64;

import java.security.GeneralSecurityException;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

// http://blog.csdn.net/randyjiawenjie/article/details/6617225
public class DES {
    private static String TAG = DES.class.getSimpleName();
    private static byte[] iv = {1, 2, 3, 4, 5, 6, 7, 8};

    public static String encrypt(String encryptString, String password) throws Exception {
//      IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);  
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        SecretKeySpec key = new SecretKeySpec(password.getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
        byte[] encryptedData = cipher.doFinal(encryptString.getBytes());

        return new String(Base64.encode(encryptedData,Base64.DEFAULT), "UTF-8");
    }

    public static String decrypt(String decryptString, String password) throws Exception {
        byte[] byteMi = Base64.decode(decryptString, Base64.DEFAULT);
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
//      IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
        SecretKeySpec key = new SecretKeySpec(password.getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
        byte decryptedData[] = cipher.doFinal(byteMi);

        return new String(decryptedData);
    }

    /* 传递cipher完成最后一步加密
    public static byte[] encryptDES(byte[] encryptString, Cipher cipher) throws Exception {
        byte[] encryptedData = cipher.doFinal(encryptString);
        return encryptedData;
    }

    public static byte[] decryptDES(byte[] decryptString, Cipher cipher) throws Exception {
        byte decryptedData[] = cipher.doFinal(decryptString);
        return decryptedData;
    }
    */


    public static Cipher encrypt_init(byte[] password) throws GeneralSecurityException {

        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        SecretKeySpec key = new SecretKeySpec(password, "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);

        return cipher;
    }

    public static Cipher decrypt_init(byte[] password) throws GeneralSecurityException {

        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        SecretKeySpec key = new SecretKeySpec(password, "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
        return cipher;
    }



}  
